//
//  SettingsView.swift
//  AppleAppDemo
//
//  Created by 刘忠华 on 2025/9/9.
//

import SwiftUI

struct SettingsView: View {
    @AppStorage("isDarkMode") private var isDarkMode = false
    @AppStorage("notificationsEnabled") private var notificationsEnabled = true
    @AppStorage("selectedLanguage") private var selectedLanguage = "zh-CN"
    @AppStorage("cacheSize") private var cacheSize = "0 MB"
    @EnvironmentObject var focusManager: TVFocusManager
    
    private let languages = [
        ("zh-CN", "简体中文"),
        ("en-US", "English"),
        ("ja-JP", "日本語"),
        ("ko-KR", "한국어")
    ]
    
    private var contentView: some View {
        VStack(spacing: PlatformConfig.spacing(for: .tvOS, base: 24)) {
            // 外观设置
            VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: .tvOS, base: 16)) {
                Text("外观设置")
                    .font(.custom("PingFangSC-Medium", size: PlatformConfig.fontSize(for: .tvOS, base: 28)))
                    .fontWeight(.bold)
                
                VStack(spacing: PlatformConfig.spacing(for: .tvOS, base: 12)) {
                    HStack {
                        Text("深色模式")
                            .font(.custom("PingFangSC-Regular", size: PlatformConfig.fontSize(for: .tvOS, base: 24)))
                        Spacer()
                        Toggle("", isOn: $isDarkMode)
                    }
                    .padding(PlatformConfig.spacing(for: .tvOS, base: 16))
                    .background(Color.gray.opacity(0.1))
                    .cornerRadius(PlatformConfig.cornerRadius(for: .tvOS, base: 12))
                }
            }
            .padding(PlatformConfig.spacing(for: .tvOS, base: 24))
            .background(Color.gray.opacity(0.05))
            .cornerRadius(PlatformConfig.cornerRadius(for: .tvOS, base: 16))
            
            // 通知设置
            VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: .tvOS, base: 16)) {
                Text("通知设置")
                    .font(.custom("PingFangSC-Medium", size: PlatformConfig.fontSize(for: .tvOS, base: 28)))
                    .fontWeight(.bold)
                
                VStack(spacing: PlatformConfig.spacing(for: .tvOS, base: 12)) {
                    HStack {
                        Text("推送通知")
                            .font(.custom("PingFangSC-Regular", size: PlatformConfig.fontSize(for: .tvOS, base: 24)))
                        Spacer()
                        Toggle("", isOn: $notificationsEnabled)
                    }
                    .padding(PlatformConfig.spacing(for: .tvOS, base: 16))
                    .background(Color.gray.opacity(0.1))
                    .cornerRadius(PlatformConfig.cornerRadius(for: .tvOS, base: 12))
                }
            }
            .padding(PlatformConfig.spacing(for: .tvOS, base: 24))
            .background(Color.gray.opacity(0.05))
            .cornerRadius(PlatformConfig.cornerRadius(for: .tvOS, base: 16))
            
            // 语言设置
            VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: .tvOS, base: 16)) {
                Text("语言设置")
                    .font(.custom("PingFangSC-Medium", size: PlatformConfig.fontSize(for: .tvOS, base: 28)))
                    .fontWeight(.bold)
                
                VStack(spacing: PlatformConfig.spacing(for: .tvOS, base: 12)) {
                    HStack {
                        Text("界面语言")
                            .font(.custom("PingFangSC-Regular", size: PlatformConfig.fontSize(for: .tvOS, base: 24)))
                        Spacer()
                        Picker("语言", selection: $selectedLanguage) {
                            ForEach(languages, id: \.0) { language in
                                Text(language.1).tag(language.0)
                            }
                        }
                        .pickerStyle(MenuPickerStyle())
                    }
                    .padding(PlatformConfig.spacing(for: .tvOS, base: 16))
                    .background(Color.gray.opacity(0.1))
                    .cornerRadius(PlatformConfig.cornerRadius(for: .tvOS, base: 12))
                }
            }
            .padding(PlatformConfig.spacing(for: .tvOS, base: 24))
            .background(Color.gray.opacity(0.05))
            .cornerRadius(PlatformConfig.cornerRadius(for: .tvOS, base: 16))
            
            // 存储设置
            VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: .tvOS, base: 16)) {
                Text("存储设置")
                    .font(.custom("PingFangSC-Medium", size: PlatformConfig.fontSize(for: .tvOS, base: 28)))
                    .fontWeight(.bold)
                
                VStack(spacing: PlatformConfig.spacing(for: .tvOS, base: 12)) {
                    HStack {
                        Text("缓存大小")
                            .font(.custom("PingFangSC-Regular", size: PlatformConfig.fontSize(for: .tvOS, base: 24)))
                        Spacer()
                        Text(cacheSize)
                            .font(.custom("PingFangSC-Regular", size: PlatformConfig.fontSize(for: .tvOS, base: 20)))
                            .foregroundColor(.secondary)
                    }
                    .padding(PlatformConfig.spacing(for: .tvOS, base: 16))
                    .background(Color.gray.opacity(0.1))
                    .cornerRadius(PlatformConfig.cornerRadius(for: .tvOS, base: 12))
                    
                    Button("清理缓存") {
                        clearCache()
                    }
                    .font(.custom("PingFangSC-Medium", size: PlatformConfig.fontSize(for: .tvOS, base: 20)))
                    .foregroundColor(.blue)
                    .padding(PlatformConfig.spacing(for: .tvOS, base: 16))
                    .background(Color.blue.opacity(0.1))
                    .cornerRadius(PlatformConfig.cornerRadius(for: .tvOS, base: 12))
                }
            }
            .padding(PlatformConfig.spacing(for: .tvOS, base: 24))
            .background(Color.gray.opacity(0.05))
            .cornerRadius(PlatformConfig.cornerRadius(for: .tvOS, base: 16))
            
            // 设备信息
            VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: .tvOS, base: 16)) {
                Text("设备信息")
                    .font(.custom("PingFangSC-Medium", size: PlatformConfig.fontSize(for: .tvOS, base: 28)))
                    .fontWeight(.bold)
                
                VStack(spacing: PlatformConfig.spacing(for: .tvOS, base: 12)) {
                    InfoRow(title: "设备类型", value: deviceTypeDescription)
                    InfoRow(title: "系统版本", value: systemVersion)
                    InfoRow(title: "应用版本", value: "1.0.0")
                    InfoRow(title: "构建版本", value: "1")
                }
            }
            .padding(PlatformConfig.spacing(for: .tvOS, base: 24))
            .background(Color.gray.opacity(0.05))
            .cornerRadius(PlatformConfig.cornerRadius(for: .tvOS, base: 16))
        }
        .padding(PlatformConfig.spacing(for: .tvOS, base: 24))
    }
    
    var body: some View {
        Group {
            if PlatformDetector.isTVOS {
                TVScrollViewWrapper(pageIndex: 2) {
                    contentView
                }
                .onAppear {
                    // 设置页面出现时，确保焦点管理器知道当前在内容区域
                    focusManager.setCurrentPageIndex(2)
                    focusManager.requestContentFocus()
                }
            } else {
                List {
                    // 外观设置
            Section("外观") {
                Toggle("深色模式", isOn: $isDarkMode)
                    #if !os(tvOS)
                    .toggleStyle(SwitchToggleStyle(tint: .blue))
                    #endif
                
                if PlatformDetector.isMacOS {
                    Picker("主题", selection: $isDarkMode) {
                        Text("浅色").tag(false)
                        Text("深色").tag(true)
                        Text("跟随系统").tag(false) // 这里可以添加系统主题检测
                    }
                    .pickerStyle(SegmentedPickerStyle())
                }
            }
            
            // 通知设置
            Section("通知") {
                Toggle("推送通知", isOn: $notificationsEnabled)
                    #if !os(tvOS)
                    .toggleStyle(SwitchToggleStyle(tint: .green))
                    #endif
                
                if notificationsEnabled {
                    NavigationLink("通知设置") {
                        NotificationSettingsView()
                    }
                }
            }
            
            // 语言设置
            Section("语言") {
                Picker("语言", selection: $selectedLanguage) {
                    ForEach(languages, id: \.0) { language in
                        Text(language.1).tag(language.0)
                    }
                }
                #if !os(tvOS)
                .pickerStyle(MenuPickerStyle())
                #endif
            }
            
            // 存储设置
            Section("存储") {
                HStack {
                    Text("缓存大小")
                    Spacer()
                    Text(cacheSize)
                        .foregroundColor(.secondary)
                }
                
                Button("清理缓存") {
                    clearCache()
                }
                .foregroundColor(.red)
            }
            
            // 平台信息
            Section("平台信息") {
                PlatformInfoRow(title: "当前平台", value: PlatformDetector.current.displayName)
                PlatformInfoRow(title: "设备类型", value: deviceTypeDescription)
                PlatformInfoRow(title: "输入方式", value: inputMethodDescription)
                PlatformInfoRow(title: "支持触控", value: PlatformDetector.current.supportsTouch ? "是" : "否")
                PlatformInfoRow(title: "支持鼠标", value: PlatformDetector.current.supportsMouse ? "是" : "否")
                PlatformInfoRow(title: "支持遥控器", value: PlatformDetector.current.supportsRemote ? "是" : "否")
            }
            
            // 关于
            Section("关于") {
                NavigationLink("关于应用") {
                    AboutView()
                }
                
                NavigationLink("隐私政策") {
                    PrivacyPolicyView()
                }
                
                NavigationLink("使用条款") {
                    TermsOfServiceView()
                }
            }
            
            // 调试信息（仅在 Debug 模式下显示）
            #if DEBUG
            Section("调试") {
                Button("重置所有设置") {
                    resetAllSettings()
                }
                .foregroundColor(.red)
                
                Button("导出日志") {
                    exportLogs()
                }
                .foregroundColor(.blue)
            }
            #endif
                }
                .navigationTitle("设置")
                #if os(iOS)
                .navigationBarTitleDisplayMode(.large)
                #endif
                .preferredColorScheme(isDarkMode ? .dark : .light)
            }
        }
        .navigationTitle("设置")
        #if os(iOS)
        .navigationBarTitleDisplayMode(.large)
        #endif
        .preferredColorScheme(isDarkMode ? .dark : .light)
    }
    
    private var deviceTypeDescription: String {
        if PlatformDetector.current.isMobile {
            return "移动设备"
        } else if PlatformDetector.current.isDesktop {
            return "桌面设备"
        } else if PlatformDetector.current.isTV {
            return "电视设备"
        }
        return "未知设备"
    }
    
    private var systemVersion: String {
        #if os(iOS) || os(tvOS)
        return UIDevice.current.systemVersion
        #elseif os(macOS)
        return ProcessInfo.processInfo.operatingSystemVersionString
        #else
        return "未知版本"
        #endif
    }
    
    private var inputMethodDescription: String {
        var methods: [String] = []
        
        if PlatformDetector.current.supportsTouch {
            methods.append("触控")
        }
        if PlatformDetector.current.supportsMouse {
            methods.append("鼠标")
        }
        if PlatformDetector.current.supportsRemote {
            methods.append("遥控器")
        }
        
        return methods.isEmpty ? "无" : methods.joined(separator: "、")
    }
    
    private func clearCache() {
        // 模拟清理缓存
        cacheSize = "0 MB"
        
        // 这里可以添加实际的缓存清理逻辑
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            // 可以添加成功提示
        }
    }
    
    private func resetAllSettings() {
        isDarkMode = false
        notificationsEnabled = true
        selectedLanguage = "zh-CN"
        cacheSize = "0 MB"
    }
    
    private func exportLogs() {
        // 这里可以添加日志导出逻辑
        print("导出日志功能")
    }
}

/// 平台信息行
struct PlatformInfoRow: View {
    let title: String
    let value: String
    
    var body: some View {
        HStack {
            Text(title)
            Spacer()
            Text(value)
                .foregroundColor(.secondary)
        }
    }
}

/// 通知设置视图
struct NotificationSettingsView: View {
    @AppStorage("pushNotifications") private var pushNotifications = true
    @AppStorage("emailNotifications") private var emailNotifications = false
    @AppStorage("soundEnabled") private var soundEnabled = true
    @AppStorage("badgeEnabled") private var badgeEnabled = true
    
    var body: some View {
        List {
            Section("通知类型") {
                Toggle("推送通知", isOn: $pushNotifications)
                Toggle("邮件通知", isOn: $emailNotifications)
            }
            
            Section("通知样式") {
                Toggle("声音", isOn: $soundEnabled)
                Toggle("角标", isOn: $badgeEnabled)
            }
            
            Section("通知时间") {
                // 这里可以添加通知时间设置
                Text("全天接收通知")
                    .foregroundColor(.secondary)
            }
        }
        .navigationTitle("通知设置")
        #if os(iOS)
        .navigationBarTitleDisplayMode(.inline)
        #endif
    }
}

/// 关于视图
struct AboutView: View {
    var body: some View {
        ScrollView {
            VStack(spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 24)) {
                // 应用图标和名称
                VStack(spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 16)) {
                    Image(systemName: "app.fill")
                        .font(.system(size: PlatformConfig.fontSize(for: PlatformDetector.current, base: 80)))
                        .foregroundColor(.blue)
                    
                    Text("AppleAppDemo")
                        .font(.largeTitle)
                        .fontWeight(.bold)
                    
                    Text("版本 1.0.0")
                        .font(.subheadline)
                        .foregroundColor(.secondary)
                }
                
                // 应用描述
                VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 12)) {
                    Text("应用描述")
                        .font(.headline)
                        .fontWeight(.semibold)
                    
                    Text("AppleAppDemo 是一个展示多平台开发能力的演示应用。它使用 SwiftUI 构建，支持 iOS、iPadOS、macOS 和 tvOS 平台，展示了如何用一套代码为不同平台提供优秀的用户体验。")
                        .font(.body)
                        .foregroundColor(.secondary)
                }
                
                // 开发信息
                VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 8)) {
                    Text("开发信息")
                        .font(.headline)
                        .fontWeight(.semibold)
                    
                    PlatformInfoRow(title: "开发者", value: "刘忠华")
                    PlatformInfoRow(title: "构建版本", value: "1.0.0 (1)")
                    PlatformInfoRow(title: "支持平台", value: "iOS 17.0+, macOS 14.0+, tvOS 17.0+")
                    PlatformInfoRow(title: "开发语言", value: "Swift 5.0")
                    PlatformInfoRow(title: "UI 框架", value: "SwiftUI")
                }
                
                Spacer()
            }
            .padding(PlatformConfig.spacing(for: PlatformDetector.current, base: 20))
        }
        .navigationTitle("关于")
        #if os(iOS)
        .navigationBarTitleDisplayMode(.inline)
        #endif
    }
}

/// 隐私政策视图
struct PrivacyPolicyView: View {
    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 16)) {
                Text("隐私政策")
                    .font(.largeTitle)
                    .fontWeight(.bold)
                
                Text("最后更新：2025年9月9日")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                
                Group {
                    Text("我们重视您的隐私")
                        .font(.headline)
                        .fontWeight(.semibold)
                    
                    Text("本应用不会收集、存储或传输您的个人数据。所有数据都存储在您的设备本地。")
                    
                    Text("数据使用")
                        .font(.headline)
                        .fontWeight(.semibold)
                    
                    Text("• 应用设置仅存储在您的设备本地\n• 不会向第三方分享任何数据\n• 不会进行用户行为追踪")
                    
                    Text("联系我们")
                        .font(.headline)
                        .fontWeight(.semibold)
                    
                    Text("如果您对本隐私政策有任何疑问，请通过应用内反馈功能联系我们。")
                }
                .font(.body)
                .foregroundColor(.secondary)
                
                Spacer()
            }
            .padding(PlatformConfig.spacing(for: PlatformDetector.current, base: 20))
        }
        .navigationTitle("隐私政策")
        #if os(iOS)
        .navigationBarTitleDisplayMode(.inline)
        #endif
    }
}

/// 使用条款视图
struct TermsOfServiceView: View {
    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: PlatformConfig.spacing(for: PlatformDetector.current, base: 16)) {
                Text("使用条款")
                    .font(.largeTitle)
                    .fontWeight(.bold)
                
                Text("最后更新：2025年9月9日")
                    .font(.subheadline)
                    .foregroundColor(.secondary)
                
                Group {
                    Text("接受条款")
                        .font(.headline)
                        .fontWeight(.semibold)
                    
                    Text("通过使用本应用，您同意遵守以下使用条款。")
                    
                    Text("使用许可")
                        .font(.headline)
                        .fontWeight(.semibold)
                    
                    Text("本应用仅供演示和学习目的使用。您可以自由使用、修改和分发本应用的源代码。")
                    
                    Text("免责声明")
                        .font(.headline)
                        .fontWeight(.semibold)
                    
                    Text("本应用按原样提供，不提供任何明示或暗示的保证。开发者不对使用本应用造成的任何损失承担责任。")
                    
                    Text("联系我们")
                        .font(.headline)
                        .fontWeight(.semibold)
                    
                    Text("如果您对这些条款有任何疑问，请通过应用内反馈功能联系我们。")
                }
                .font(.body)
                .foregroundColor(.secondary)
                
                Spacer()
            }
            .padding(PlatformConfig.spacing(for: PlatformDetector.current, base: 20))
        }
        .navigationTitle("使用条款")
        #if os(iOS)
        .navigationBarTitleDisplayMode(.inline)
        #endif
    }
}


#Preview {
    NavigationView {
        SettingsView()
    }
}
